package org.itboys.ace.web;

import org.apache.commons.collections.CollectionUtils;
import org.itboys.admin.constant.AdminConstants;
import org.itboys.admin.dto.AdminUserDTO;
import org.itboys.admin.entity.AdminRole;
import org.itboys.admin.entity.GlobalConfigDB;
import org.itboys.admin.entity.GlobalConfigRecordDB;
import org.itboys.admin.service.AdminRoleService;
import org.itboys.admin.service.AdminUserService;
import org.itboys.admin.service.GlobalConfigRecordService;
import org.itboys.admin.service.GlobalConfigService;
import org.itboys.admin.tools.AdminSessionHolder;
import org.itboys.admin.tools.LoginUser;
import org.itboys.commons.CommonConstants;
import org.itboys.commons.utils.ajax.AjaxUtils;
import org.itboys.framework.query.JsonPageUtils;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.mongodb.utils.page.Page;
import org.itboys.seller.dto.SiteUserVO;
import org.itboys.seller.entity.SiteUserEdit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 参数模板
 * 
 * @author huanglei
 *
 */
@RestController
@RequestMapping("/ace/sys/global")
public class AceSysConfigController extends BaseController{

	@Autowired
	private GlobalConfigService globalConfigService;

	@Autowired
	private GlobalConfigRecordService globalConfigRecordService;

	@Autowired
	private AdminUserService adminUserService;

	@Autowired
	private AdminRoleService adminRoleService;

	/**
	 * 进入全局配置页面
	 */
	@RequestMapping("/config")
	public ModelAndView toGlobalConfig(Model model,HttpServletRequest request){
		List<GlobalConfigDB> globalConfigDBs = globalConfigService.getAllConfigs();
		Map<String, GlobalConfigDB> globalConfigDBMap = globalConfigDBs.stream().collect(Collectors.toMap(p -> p.getKey(), p ->p));
		for (GlobalConfigDB globalConfigDB : globalConfigDBs) {
			model.addAttribute(globalConfigDB.getKey(), globalConfigDB.getValue());
			model.addAttribute(globalConfigDB.getKey()+"Id", globalConfigDB.getId());
		}
		LoginUser user = AdminSessionHolder.getAdminLoginUser();
		if (user.getType() != AdminConstants.TYPE_SUPER && CollectionUtils.isNotEmpty(user.getRoleIds())) {
			List<AdminRole> adminRoles = adminRoleService.getByIds(user.getRoleIds());
			if (adminRoles.size() == 1 && "查看员".equals(adminRoles.get(0).getName())) {
				model.addAttribute("readOnly", 1);
			}
		}
		return new ModelAndView("ace/admin/global-config");

	}

	/**
	 * 保存全局配置
	 */
	@RequestMapping("/saveGlobalConfig")
	public void saveGlobalConfig(int minCommision,
								 int maxCommision,
								 int rewardLine,
                                 int minScore,
                                 int sRewardLine, int sMinScore,
                                 int ssRewardLine, int ssMinScore,
                                 int dayRecharge,
                                 int maxSubScore,
								 HttpServletRequest request,HttpServletResponse response) {
		AdminUserDTO user = adminUserService.getUserById(AdminSessionHolder
				.getAdminUserId());
		if (user == null||user.getAdminUser() == null) {
			AjaxUtils.renderText(response, CommonConstants.FAIL);
			return;
		}
		GlobalConfigRecordDB globalConfigDB = new GlobalConfigRecordDB();
		globalConfigDB.setMinCommision(minCommision);
		globalConfigDB.setMaxCommision(maxCommision);
		globalConfigDB.setRewardLine(rewardLine);
		globalConfigDB.setUsername(user.getAdminUser().getUsername());
        globalConfigDB.setMinScore(minScore);
        globalConfigDB.setsRewardLine(sRewardLine);
        globalConfigDB.setSsRewardLine(ssRewardLine);
        globalConfigDB.setsMinScore(sMinScore);
        globalConfigDB.setSsMinScore(ssMinScore);
        globalConfigDB.setDayRecharge(dayRecharge);
        globalConfigDB.setMaxSubScore(maxSubScore);
		globalConfigRecordService.save(globalConfigDB);
		AjaxUtils.renderText(response, CommonConstants.SUCCESS);

	}

	/**
	 * 进入冻结审核页面
	 */
	@RequestMapping("/audit-list")
	public ModelAndView userFrozen(Model model,HttpServletRequest request){
		return new ModelAndView("ace/admin/global-audit");

	}

	/**
	 * 分页查询待审核记录
	 *
	 * @return
	 */
	@RequestMapping("/auditlist")
	public void auditlist(HttpServletRequest request, HttpServletResponse response) {
		Page<GlobalConfigRecordDB> page = globalConfigRecordService.pageQueryAll(request);
		JsonPageUtils.renderJsonPage(page.getTotal(),page.getTotalPages(), page.getData(), response);
	}

	/**
	 * 审核
	 */
	@RequestMapping(value = "/audit", method= RequestMethod.POST)
	public void audit(@RequestParam(value = "recordId", required = true) long recordId,
								@RequestParam(value = "pass", required = true) boolean pass,
								HttpServletRequest request, HttpServletResponse response) {
		AdminUserDTO user = adminUserService.getUserById(AdminSessionHolder
				.getAdminUserId());
		if (user == null||user.getAdminUser() == null) {
			AjaxUtils.renderText(response, CommonConstants.FAIL);
			return;
		}
		GlobalConfigRecordDB globalConfigRecordDB = globalConfigRecordService.getById(recordId);
		if (globalConfigRecordDB == null) {
			AjaxUtils.renderText(response, CommonConstants.FAIL);
			return;
		}
		globalConfigRecordDB.setAuditState(pass ? 1 : 2);
		globalConfigRecordDB.setAuditName(user.getAdminUser().getRealName());
		globalConfigRecordService.update(globalConfigRecordDB);
		if (!pass) {
			AjaxUtils.renderText(response, CommonConstants.SUCCESS);
			return;
		}

		GlobalConfigDB globalConfigDB = globalConfigService.getByField("key", "minCommision");
		if (globalConfigDB == null) {
			globalConfigDB = new GlobalConfigDB();
			globalConfigDB.setKey("minCommision");
		}
		globalConfigDB.setValue(globalConfigRecordDB.getMinCommision());
		if (globalConfigDB.getId() != 0) {
			globalConfigService.update(globalConfigDB);
		} else {
			globalConfigService.save(globalConfigDB);
		}

		globalConfigDB = globalConfigService.getByField("key", "maxCommision");
		if (globalConfigDB == null) {
			globalConfigDB = new GlobalConfigDB();
			globalConfigDB.setKey("maxCommision");
		}
		globalConfigDB.setValue(globalConfigRecordDB.getMaxCommision());
		if (globalConfigDB.getId() != 0) {
			globalConfigService.update(globalConfigDB);
		} else {
			globalConfigService.save(globalConfigDB);
		}

		globalConfigDB = globalConfigService.getByField("key", "rewardLine");
		if (globalConfigDB == null) {
			globalConfigDB = new GlobalConfigDB();
			globalConfigDB.setKey("rewardLine");
		}
		globalConfigDB.setValue(globalConfigRecordDB.getRewardLine());
		if (globalConfigDB.getId() != 0) {
			globalConfigService.update(globalConfigDB);
		} else {
			globalConfigService.save(globalConfigDB);
		}

        globalConfigDB = globalConfigService.getByField("key", "minScore");
        if (globalConfigDB == null) {
            globalConfigDB = new GlobalConfigDB();
            globalConfigDB.setKey("minScore");
        }
        globalConfigDB.setValue(globalConfigRecordDB.getMinScore());
        if (globalConfigDB.getId() != 0) {
            globalConfigService.update(globalConfigDB);
        } else {
            globalConfigService.save(globalConfigDB);
        }

        globalConfigDB = globalConfigService.getByField("key", "dayRecharge");
        if (globalConfigDB == null) {
            globalConfigDB = new GlobalConfigDB();
            globalConfigDB.setKey("dayRecharge");
        }
        globalConfigDB.setValue(globalConfigRecordDB.getDayRecharge());
        if (globalConfigDB.getId() != 0) {
            globalConfigService.update(globalConfigDB);
        } else {
            globalConfigService.save(globalConfigDB);
        }

        globalConfigDB = globalConfigService.getByField("key", "sRewardLine");
        if (globalConfigDB == null) {
            globalConfigDB = new GlobalConfigDB();
            globalConfigDB.setKey("sRewardLine");
        }
        globalConfigDB.setValue(globalConfigRecordDB.getsRewardLine());
        if (globalConfigDB.getId() != 0) {
            globalConfigService.update(globalConfigDB);
        } else {
            globalConfigService.save(globalConfigDB);
        }

        globalConfigDB = globalConfigService.getByField("key", "sMinScore");
        if (globalConfigDB == null) {
            globalConfigDB = new GlobalConfigDB();
            globalConfigDB.setKey("sMinScore");
        }
        globalConfigDB.setValue(globalConfigRecordDB.getsMinScore());
        if (globalConfigDB.getId() != 0) {
            globalConfigService.update(globalConfigDB);
        } else {
            globalConfigService.save(globalConfigDB);
        }

        globalConfigDB = globalConfigService.getByField("key", "ssRewardLine");
        if (globalConfigDB == null) {
            globalConfigDB = new GlobalConfigDB();
            globalConfigDB.setKey("ssRewardLine");
        }
        globalConfigDB.setValue(globalConfigRecordDB.getSsRewardLine());
        if (globalConfigDB.getId() != 0) {
            globalConfigService.update(globalConfigDB);
        } else {
            globalConfigService.save(globalConfigDB);
        }

        globalConfigDB = globalConfigService.getByField("key", "ssMinScore");
        if (globalConfigDB == null) {
            globalConfigDB = new GlobalConfigDB();
            globalConfigDB.setKey("ssMinScore");
        }
        globalConfigDB.setValue(globalConfigRecordDB.getSsMinScore());
        if (globalConfigDB.getId() != 0) {
            globalConfigService.update(globalConfigDB);
        } else {
            globalConfigService.save(globalConfigDB);
        }

        globalConfigDB = globalConfigService.getByField("key", "dayRecharge");
        if (globalConfigDB == null) {
            globalConfigDB = new GlobalConfigDB();
            globalConfigDB.setKey("dayRecharge");
        }
        globalConfigDB.setValue(globalConfigRecordDB.getDayRecharge());
        if (globalConfigDB.getId() != 0) {
            globalConfigService.update(globalConfigDB);
        } else {
            globalConfigService.save(globalConfigDB);
        }

        globalConfigDB = globalConfigService.getByField("key", "maxSubScore");
        if (globalConfigDB == null) {
            globalConfigDB = new GlobalConfigDB();
            globalConfigDB.setKey("maxSubScore");
        }
        globalConfigDB.setValue(globalConfigRecordDB.getMaxSubScore());
        if (globalConfigDB.getId() != 0) {
            globalConfigService.update(globalConfigDB);
        } else {
            globalConfigService.save(globalConfigDB);
        }
		AjaxUtils.renderText(response, CommonConstants.SUCCESS);

	}
}
